# 添加错误日志截图
import pytest
from selenium import webdriver
import os
import allure

# 设置全局的driver
driver = None


# 添加钩子函数
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    '''
    钩子函数
    :param item:
    :param call:
    :return:
    '''
    # 获得html对象
    pytest_html = item.config.pluginmanager.getplugin("html")
    # 获取result对象
    outcome = yield
    # 获得report报告
    report = outcome.get_result()
    extra = getattr(report, "extra", [])
    # 设置错误截图
    if report.when == "call":
        xfail = hasattr(report, 'wasfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            # 使用allure进行错误截图
            with allure.step('添加失败截图'):
                driver = webdriver.Chrome()
                allure.attach(driver.get_screenshot_as_png(), '失败截图', allure.attachment_type.PNG)
    #     # 根据用例名称设置截图名称
    #     image_name = report.nodeid.split("::")[1] + '.png'
    #     # 调用错误截图方法
    #     image_path = get_picture(image_name)
    #     # 设置对应的html
    #     if image_path:
    #         html = f'<div><img src="{image_path}" alt="screenshot" style="width:304px;height:228px"' \
    #                ' onclick="window.open(this.src)" align="right"/></div>'
    #         # 将html添加到测试报告当中
    #         extra.append(pytest_html.extras.html(html))
    #
    # report.extra = extra


def get_picture(image_name):
    '''
    获取错误截图
    :return:
    '''
    global driver
    # 设置截图的路径
    project_path = os.path.dirname(__file__)
    image_path = os.path.join(project_path, r"report", image_name)
    # 添加截图
    driver.save_screenshot(image_path)
    return image_path


@pytest.fixture(scope='session', autouse=True)
def browser():
    '''
    设置全局的fixture
    :return:
    '''
    global driver
    driver = webdriver.Chrome()
    yield driver
    driver.quit()


if __name__ == '__main__':
    get_picture('dad.png')
